<?php
/**
 * Created by PhpStorm.
 * User: iiinsomnia
 * Date: 2017/11/25
 * Time: 17:41
 */
namespace App\Http\Controllers;

use App\Models\User;
use App\Service\UserService;
use EasyWeChat\Foundation\Application;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;

class UserController extends Controller
{
    protected $user;

    function __construct(UserService $user) {
        $this->user = $user;
    }

    public function add(Request $request, Application $application) {
        $this->validate($request, [
            'code' => 'required|string',
            'nickname' => 'required|string',
            'head_img' => 'required|string'
        ]);
        $minapp = $application->mini_program;
        $session = $minapp->sns->getSessionKey($request->get('code'));
        $open_id = $session->get('openid');
        $session_key = $session->get('session_key');
        if(!$session_key || !$open_id){
            return self::responseError(1004, '授权失败');
        }
        $token = str_random(32);
        $token_user = User::whereOpenId($open_id)->first();
        if(!$token_user){
            $token_user = new User();
            $token_user->name = $request->get('nickname');
            $token_user->head_img_url = $request->get('head_img');
            $token_user->open_id = $open_id;
            $token_user->session_code = $session_key;
            $token_user->token = $token;
            $token_user->save();
        }else{
            $token_user->session_code = $session_key;
            $token_user->token = $token;
            $token_user->save();
        }
        return self::responseSuccess($token_user);
    }


    public function loginUser(){
        return self::responseSuccess(UserService::authUser());
    }

}